package cn.ee.dfs.common.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Describe : 网络请求
 * Created by TWJ on 2019/6/17 0017 下午 2:40
 */
@Component
public class NetTool {
    private static Logger lg = LoggerFactory.getLogger(NetTool.class);
//    If the annotation is applied to the component class,
//   the annotation declares a resource that the application will look up at runtime

    private static OkHttpClient okHttpClient;

    @Autowired
    public NetTool(OkHttpClient okHttpClient) {
        NetTool.okHttpClient = okHttpClient;
    }

//    public String CONTENT_TYPE_STREAM = "application/octet-stream";
//    public  String CONTENT_TYPE_STREAM = "application/octet-stream";
//    public  String CONTENT_TYPE_STREAM = "application/octet-stream";
//    public  String CONTENT_TYPE_STREAM = "application/octet-stream";

    /**
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     */
    public static String get(String url, Map<String, String> queries, boolean throwEx) {
        StringBuilder sb = new StringBuilder(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = url.contains("?") ? false : true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        Request request = new Request
                .Builder()
                .url(sb.toString())
                .build();
        lg.info(" get request url:" + url);
        lg.info(" get request params:" + queries);
        if (throwEx)
            return getResultThrowException(request);
        else
            return getResult(request);
    }

    /**
     * @param url 请求的url
     */
    public static String get(String url, boolean throwEx) {
        Request request = new Request
                .Builder()
                .url(url)
                .build();
        lg.info(" get request url:" + url);
        if (throwEx)
            return getResultThrowException(request);
        else
            return getResult(request);
    }

    public static String get(String url) {

        return get(url, false);
    }


    public static String get(String url, Map<String, String> queries) {
        return get(url, queries, false);
    }

    /**
     * POST
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     */
    public static String post(String url, Map<String, String> params, boolean throwEx) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                if (StringUtils.isEmpty(value)) value = "";
                builder.add(key, value);
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();

        lg.info(" post request url:" + url);
        lg.info(" post request params:" + params);
        if (throwEx)
            return getResultThrowException(request);
        else
            return getResult(request);
    }

    public static String post(String url, Map<String, String> params) {
        return post(url, params, false);
    }

    private static String getResult(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            lg.info("请求  错误...");
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }


    private static String getResultThrowException(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }


    /**
     * post 上传文件
     *
     * @param fileType 文件类型
     */
    public String postFile(String url, Map<String, Object> params, String fileType) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            Set<String> strings = params.keySet();
            for (String key : strings) {
                if (params.get(key) instanceof File) {
                    File file = (File) params.get(key);
                    lg.info("---postFile-----" + file.getName());
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
                    continue;
                }
                builder.addFormDataPart(key, params.get(key).toString());
            }
        }
        builder.setType(MultipartBody.FORM);//    表单提交类型
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        lg.info("----------------" + builder.build().toString());
        return getResult(request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        return getResult(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams, boolean throwEx) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        if (throwEx)
            return getResultThrowException(request);
        else
            return getResult(request);
    }

    public static String postJsonParams(String url, String jsonParams) {
        return postJsonParams(url, jsonParams, false);
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String getForHeader(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .addHeader("key", "value")
                .url(sb.toString())
                .build();

        return getResult(request);
    }

}
